package cn.hpu.mobile_bank.interceptor;

import cn.hpu.mobile_bank.constant.RedisConstants;
import cn.hpu.mobile_bank.domain.PersonInfo;
import cn.hpu.mobile_bank.dto.req.RequestInfo;
import cn.hpu.mobile_bank.utils.RequestHolder;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;

import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;
import java.util.concurrent.TimeUnit;


@Slf4j
public class RefreshTokenInterceptor implements HandlerInterceptor {

    private StringRedisTemplate stringRedisTemplate;

    //手动创建的对象(例如每加Configuration的类)需要手动注入，不能依靠注解注入
    public RefreshTokenInterceptor(StringRedisTemplate stringRedisTemplate) {
        this.stringRedisTemplate = stringRedisTemplate;
    }

    //前置拦截器
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //1.获取请求头中的token
        String token = request.getHeader("Token");
        //如果token为空
        if (StrUtil.isBlank(token)) {
            return true;
        }

        //2.基于token获取redis中的用户
        Map<Object, Object> userMap = stringRedisTemplate.opsForHash().entries(RedisConstants.LOGIN_USER_KEY + token);

        //3.判断用户是否存在
        if(userMap.isEmpty()){
            return true;
        }

        //5.将查询到的hash数据转为userDto对象
        //第三个参数是 是否忽略转换过程中的错误
//        PersonInfo personInfo = BeanUtil.fillBeanWithMap(userMap, new PersonInfo(), false);
        //6.存在，保存用户信息到ThreadLocal
        RequestHolder.set(new RequestInfo(Integer.parseInt((String) userMap.get("personId")) , (String) userMap.get("telephone")));

        //7.刷新token有效期。(只要有访问，就会刷新有效期，防止过期，只有超过30分钟没有访问才会过期)
        stringRedisTemplate.expire(RedisConstants.LOGIN_USER_KEY + token, RedisConstants.LOGIN_USER_TTL, TimeUnit.MINUTES);

        //8.放行
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        //移除用户
        RequestHolder.remove();
    }
}
